package com.yt.order.service;


import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import com.yt.common.constant.Result;
import com.yt.common.enums.CodeEnum;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;

@Service
public class FastDFSService {

    @Resource
    private FastFileStorageClient storageClient;

    /**
     * 上传文件到FastDFS
     * @param file 上传的文件
     * @return 包含文件访问URL的结果
     */
    public Result<String> uploadFile(MultipartFile file) {
        try {
            // 验证文件
            if (file.isEmpty()) {
                return new Result<>(CodeEnum.FAIL_100002.getCode(), "上传文件不能为空");
            }

            // 获取文件扩展名
            String originalFilename = file.getOriginalFilename();
            String fileExtName = originalFilename.substring(originalFilename.lastIndexOf(".") + 1);

            // 上传文件
            StorePath storePath = storageClient.uploadFile(
                    file.getInputStream(),
                    file.getSize(),
                    fileExtName,
                    null
            );

            // 构建文件访问URL
            String fileUrl = "http://47.96.93.244:8084/" + storePath.getFullPath();
            return new Result<>(fileUrl);

        } catch (IOException e) {
            return new Result<>(CodeEnum.FAIL_100012.getCode(), "文件上传失败：" + e.getMessage());
        } catch (Exception e) {
            return new Result<>(CodeEnum.FAIL_100001.getCode(), "文件上传异常：" + e.getMessage());
        }
    }

    /**
     * 删除FastDFS中的文件
     * @param fileUrl 文件访问URL
     * @return 操作结果
     */
    public Result<Void> deleteFile(String fileUrl) {
        try {
            // 解析文件路径
            String fullPath = fileUrl.substring(fileUrl.indexOf("/group"));
            StorePath storePath = StorePath.parseFromUrl(fullPath);

            // 删除文件
            storageClient.deleteFile(storePath.getGroup(), storePath.getPath());
            return new Result<>();
        } catch (Exception e) {
            return new Result<>(CodeEnum.FAIL_100013.getCode(), "文件删除失败：" + e.getMessage());
        }
    }
}